class Cartasur::Answer < Cartasur::CartasurModel

  belongs_to :question, :class_name => 'Cartasur::Question'
  belongs_to :protocol, :class_name => 'Cartasur::Protocol'

attr_accessible :value, :question_id, :answer_type, :protocol_id

    #instance methods
  #get the question and answer text in a friendly format
  def friendly_question_answer_text

    mainquestion = self.question.text
    #get the subquestions for that  question
    subquestions = Cartasur::List.getlist(Cartasur::List::TYPES[:questions], self.question.id).all
    res = []
    if self.answer_type !~ /checkbox/ and self.answer_type !~ /text/
     #we want to get the question for each number answer value

      answers = self.value.split(/,/)
      answers.each_with_index do |ans,idx|
        #get the subquestion
        res << {qn: subquestions[idx], value: ans}
      end

    else

      #value for checkbox, leave it as it is
      res << {qn: nil, value: self.value}
    end

    {mainqn: mainquestion, subqns: res}
  end

    #class methods
    def self.savefromxml(xml_doc)
      svroot = REXML::XPath.first( xml_doc, "//survey")
      protocol_id = svroot.attribute("protocol_id").try(:value)

      answers = []

      REXML::XPath.each( xml_doc, "//question"){ |measurement|
        ans = self.new
        ans.question_id =  measurement.attribute("id").try(:value)

        ans.answer_type = measurement.attribute("type").try(:value)

        ans.value =  measurement.attribute("answer").try(:value)

        ans.protocol_id = protocol_id

        answers << ans
      }

      begin

        #first clear if any are there
        #clear_protocol_answers(protocol_id)

        answers.each { |answer| answer.save }

      rescue Exception => ex
        logger.error("Problem when saving the answers from xml of protocol #{protocol_id}. Details: #{ex.message}")
      end

    end

    def self.clear_protocol_answers(protocol_id)
      delete_all(" protocol_id=#{protocol_id}") unless protocol_id.nil?
    end

end